package com.example.qrcodecamera;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.RGBLuminanceSource;
import java.nio.ByteBuffer;
import android.graphics.ImageFormat;
import android.media.Image;
import android.media.ImageReader;
import android.os.Handler;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class USBCameraQRActivity extends AppCompatActivity implements SurfaceHolder.Callback {
    private SurfaceView surfaceView;
    private TextView tvResult;
    private UsbManager usbManager;
    private UsbDevice usbCamera;
    private ImageReader imageReader;
    private Handler handler = new Handler();
    private Executor cameraExecutor = Executors.newSingleThreadExecutor();
    private MultiFormatReader qrCodeReader = new MultiFormatReader();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_usbcamera_qractivity);

        surfaceView = findViewById(R.id.surface_view);
        tvResult = findViewById(R.id.tv_result);
        surfaceView.getHolder().addCallback(this);

        usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        checkForUsbCameras();
    }

    // 检测 USB 摄像头
    private void checkForUsbCameras() {
        for (UsbDevice device : usbManager.getDeviceList().values()) {
            if (isUsbCamera(device)) {
                usbCamera = device;
                Toast.makeText(this, "USB Camera Detected", Toast.LENGTH_SHORT).show();
                break;
            }
        }
        if (usbCamera == null) {
            Toast.makeText(this, "No USB Camera Found!", Toast.LENGTH_SHORT).show();
        }
    }

    // 检查设备是否是 USB 摄像头
    private boolean isUsbCamera(UsbDevice device) {
        return device.getInterfaceCount() > 0 &&
                device.getInterface(0).getInterfaceClass() == 14; // USB_CLASS_VIDEO
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        setupCameraPreview(holder.getSurface());
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {}

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        if (imageReader != null) {
            imageReader.close();
        }
    }

    // 初始化摄像头预览
    private void setupCameraPreview(Surface surface) {
        imageReader = ImageReader.newInstance(
                surfaceView.getWidth(),
                surfaceView.getHeight(),
                ImageFormat.YUV_420_888,
                2
        );

        imageReader.setOnImageAvailableListener(reader -> {
            Image image = reader.acquireLatestImage();
            if (image != null) {
                cameraExecutor.execute(() -> processImageForQR(image));
                image.close();
            }
        }, null);

        // TODO: 这里需要接入 USB 摄像头数据流（如使用 libuvc 或 AndroidUSBCamera）
        // 示例伪代码：
        // usbCamera.setPreviewSurface(surface);
        // usbCamera.startPreview();
    }

    // 处理图像并检测二维码
    private void processImageForQR(Image image) {
        ByteBuffer buffer = image.getPlanes()[0].getBuffer();
        byte[] data = new byte[buffer.remaining()];
        buffer.get(data);

        int width = image.getWidth();
        int height = image.getHeight();
        int[] pixels = new int[width * height];

        // 转换为 RGB 数据（简化版，实际需处理 YUV）
        for (int i = 0; i < data.length; i++) {
            pixels[i] = data[i] & 0xFF;
        }

        RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

        try {
            Result result = qrCodeReader.decode(bitmap);
            runOnUiThread(() -> tvResult.setText("QR Code: " + result.getText()));
        } catch (Exception e) {
            Log.e("QR", "Decode error: " + e.getMessage());
        }
    }
}